package com.situ.day4;


import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;

public class TransactionalDemo {

    @Test
    public void test1() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        String sql1 = "UPDATE account SET money=money-1000 WHERE name='zhangsan'";
        String sql2 = "UPDATE account SET money=money+1000 WHERE name='lisi'";
        try {
            connection = JDBCUtil.getConnection();
            //为false，表示禁用自动提交（默认情况是true）
            //connection.setAutoCommit(false);
            preparedStatement=connection.prepareStatement(sql1);
            System.out.println(preparedStatement);
            preparedStatement.executeUpdate();
            int i = 3 / 0;
            preparedStatement = connection.prepareStatement(sql2);
            System.out.println(preparedStatement);
            preparedStatement.executeUpdate();
            //setAutoCommit(false)改成false之后，不会提交数据库，只有调用connection.commit()才提交
            //connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            /*try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }*/
        } finally {
            JDBCUtil.close(connection, preparedStatement, null);
        }
    }
}
